package com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.impl;


import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.GridAddName;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.GridFile;
import com.dmgis.qxfw.dataservice.businessservice.common.util.DateTime;
import com.dmgis.qxfw.dataservice.businessservice.common.util.FileUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.JsonUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.StringUtil;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IGridDataService;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 格点数据获取类
 *
 * @author dsq
 * @date 2019年12月23日
 */
@Service("GridDataService")
public class GridDataService implements IGridDataService {
    ProcessRequestController pc = new ProcessRequestController();
    MongoService1 ms = new MongoService1();
    @Override
    public List<Map> getGridNewestDate(String[] types) {
        List<Map> result = new ArrayList<>();
        try {
            RequestDataBySelect selectRequest = new RequestDataBySelect();
            selectRequest.setColumns(new String[]{"elementtype", "mappedpath"});
            String strWhere = "elementtype in (";
            for (int i = 0; i < types.length; i++) {
                strWhere += String.format("'%s',", types[i]);
            }
            strWhere = StringUtil.trimEnd(strWhere, ',') + ")";
            selectRequest.setParam(strWhere);
            Map<String, String> selectParam = new HashMap<String, String>();
            selectParam.put("method", "ybzz_config");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            if (!message.equals("[]")) {
                result = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<Map>>() {
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public List<GridAddName> getGridAddName() {
        List<GridAddName> result = new ArrayList<>();
        try {
            RequestDataBySelect selectRequest = new RequestDataBySelect();
            Map<String, String> selectParam = new HashMap<String, String>();
            selectParam.put("method", "grid_addname");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            if (!message.equals("[]")) {
                result = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<GridAddName>>() {
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public String[] getWindGridData(String tempFilePath, GridFile gridPrams) throws ParseException {
        DateTime forecastTime = DateTime.parseDateTime(gridPrams.getDatechar()).AddHours(Integer.parseInt(gridPrams.getTimechar()));
        String ntimes = String.format("%03d", Integer.parseInt(gridPrams.getNtimes()));
        String uFileName = "";
        String vFileName = "";//备份风格点
        String uString = ".u";
        String vString = ".v";

        if ("0".equals(gridPrams.getDatatype())) {//省台格点是大写
            uString = uString.toUpperCase();
            vString = vString.toUpperCase();
        }
        uFileName = gridPrams.getType() + uString + "." + forecastTime.toDateTimeString("yyyyMMddHH.") + ntimes;
        vFileName = uFileName.replace(uString, vString);
        //判断文件是否存在
        Boolean isExit = true;
        FileUtil.mkDirs(tempFilePath);// 创建文件夹
        // 当格点文件数量达到1000时清除
        FileUtil.ClearTempFiles(tempFilePath, 1000);
        File uGridFile = new File(tempFilePath + uFileName);
        File vGridFile = new File(tempFilePath + vFileName);
        if (!uGridFile.exists() && !vGridFile.exists()) {
            //检查mongodb是否存在该文件
            Map<String, Object> map = new HashMap<String, Object>();
            Map<String, Object> map1 = new HashMap<String, Object>();
            map.put("datechar", forecastTime.toDateString());
            map.put("timechar", forecastTime.toDateTimeString("HH"));
            map.put("ntimes", ntimes);
            map.put("type", gridPrams.getType() + uString);//风 u文件
            map.put("collectionName", "grid_file");
            byte[] data = ms.selectData(map);
            if (data != null && data.length > 10) {
                FileUtil.bytesToFile(data, uGridFile.getPath());
                //处理v文件
                map1.put("datechar", forecastTime.toDateString());
                map1.put("timechar", forecastTime.toDateTimeString("HH"));
                map1.put("ntimes", ntimes);
                map1.put("type", gridPrams.getType() + uString);//风 u文件
                map1.put("collectionName", "grid_file");
                map1.put("type", gridPrams.getType() + vString);//重新赋值修改type值
                byte[] data1 = ms.selectData(map1);
                if (data1 != null && data1.length > 0) {
                    FileUtil.bytesToFile(data1, vGridFile.getPath());//保存v文件
                }
            } else {
                isExit = false;//文件不存在
            }
        }
        if (isExit) {
            return new String[]{uGridFile.getPath(), vGridFile.getPath()};
        } else {
            return new String[]{"", ""};
        }
    }

    @Override
    public String getGridData(String tempFilePath, GridFile gridPrams) throws ParseException {
        DateTime forecastTime = DateTime.parseDateTime(gridPrams.getDatechar()).AddHours(Integer.parseInt(gridPrams.getTimechar()));
        String ntimes = String.format("%03d", Integer.parseInt(gridPrams.getNtimes()));
        String gridType = gridPrams.getType();
        String fileName = gridPrams.getType() + "." + forecastTime.toDateTimeString("yyyyMMddHH.")
                + ntimes;
        //判断文件是否存在
        Boolean isExit = true;
        FileUtil.mkDirs(tempFilePath);// 创建文件夹
        // 当格点文件数量达到1000时清除
        FileUtil.ClearTempFiles(tempFilePath, 1000);
        File gridFile = new File(tempFilePath + fileName);
        if (!gridFile.exists()) {
            //检查mongodb是否存在该文件
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", forecastTime.toDateString());
            map.put("timechar", forecastTime.toDateTimeString("HH"));
            map.put("ntimes", ntimes);
            map.put("type", gridPrams.getType());
            map.put("collectionName", "grid_file");
            byte[] data = ms.selectData(map);
            //byte[] data = HttpRequest.get(DbConfig.mongoSelectUrl, map, true).bytes();
            if (data != null && data.length > 10) {
                FileUtil.bytesToFile(data, gridFile.getPath());
            } else {
                isExit = false;//文件不存在
            }
        }
        if (isExit) {
            return gridFile.getPath();
        } else {
            return "";
        }
    }
}
